Discover scheduledexecutorservice, include the articles, news, trends, analysis and practical advice about scheduledexecutorservice on alibabacloud.com
In the previous blog, "task scheduling (iii)--timer's alternative Scheduledexecutorservice introduction" has made a brief introduction to Scheduledexecutorservice, In fact, the use of Scheduledexecutorservice to replace the timer is also a compelling thing. The main reasons are as follows:
The timer does not support multi-threading, all tasks that are su
Scheduledexecutorservice Interface
Based on executorservice, scheduledexecutorservice provides the time-based task execution function. It provides the following methods:
Schedule (task, initdelay): schedules submitted callable or runnable tasks to be executed after the time specified by initdelay.
Scheduleatfixedrate (): Schedule the submitted runnable tasks to be executed repeatedly at the specified int
1,executor, Executorservice, and Scheduledexecutorservice, they're all interfaces, Their relationship is scheduledexecutorservice inherit Executorservice and Executorservice and inherit executor.These can be seen as a bit of open source code.2, for the executor interface, it has only one method, void execute (Runnable command), and the subsequent executorservice and sch
Two ScheduledExecutorService methods,
During development, other code is often executed in another thread, and implemented using the java scheduled task interface ScheduledExecutorService.
ScheduledExecutorService is a scheduled task class designed based on the thread pool. Each scheduling task is assigned to a thread in the thread pool for execution. That is to s
First say Schedulewithfixeddelay (),
Schedulewithfixeddelay is literally understood to be a fixed delay (time) to perform the thread task, which is actually the execution time of the pipeline task, each time after the task has been completed and then delayed a fixed time before the next time.
And Schedulefixedrate, is to perform a thread task at a fixed frequency, the meaning of fixed frequency is that may set a fixed time is not enough to complete the thread task, but it does not matter, to ach
result is as follows:
task1 invoked ! 1000task2 invoked ! 4000Task 2 is actually executed after 4, because Timer is a thread internally, and the time required by Task 1 exceeds the interval between two tasks. The following uses ScheduledThreadPool to solve this problem:
Package com. zhy. concurrency. timer; import java. util. timerTask; import java. util. concurrent. executors; import java. util. concurrent. scheduledExecutorService; import java. u
Task Scheduling (4) -- ScheduledExecutorService replaces Timer to implement multi-thread task scheduling and scheduledexecutor
In the previous blog, Task Scheduling (III)-Introduction to ScheduledExecutorService, a substitute for Timer, has introduced ScheduledExecutorService briefly. In fact, it is imperative to use Schedule
First, Scheduledexecutorservice design thoughtScheduledexecutorservice is a timed task class based on thread pool design, where each dispatch task is assigned to a thread in the thread pool to execute, that is, the task is executed concurrently and does not affect each other.It is important to note that Scheduledexecutorservice only actually starts a thread when the dispatch task comes, and the rest of the
Scheduledexecutorservice extends the Executorservice interface, providing the ability to perform tasks regularly (like a timer). API Description
method
Desc
Schedule (callable
Creates and executes a scheduledfuture that is enabled after a given delay.
Schedule (Runnable command, long delay, timeunit unit)
Creates and executes a one-time operation that is enabled after a given delay.
Sc
modified later, the program will continue to be executed based on taskfired = (executiontime
2. Since jdk1.5 is started, we can select scheduledexecutorservice to replace timer for scheduled tasks. Scheduledexecutorservice is not based on absolute time and cycle, but on time delay and cycle. In this way, when a time jump occurs (Network Delay/time server synchronization/manual intervention ), the sche
After Java5, the concurrent Threads section adds a lot of new things, a new start, dispatch, and management thread of a lot of API, at this time through executor to start the thread than Thread.Start () better, easier to control thread startup, destruction, etc., can also use the function of the thread pool.I. Creating a Taskis actually implementing the Runnable interface to implement the Run method.Two. Perform TasksThe task is performed through the Java.util.concurrent.ExecutorService interfac
implement, the specific invocation method is as follows:
Timer timer = new timer ();
Systemtimertask () task = new Systemtimertask (10001,20);
About the schedule method declared as: Schedule (timertask task, long delay, long period)
--task: Scheduled task;
--delay: In milliseconds, indicates that the task is delayed delay milliseconds after execution;
--period: In milliseconds, the duration of the task execution, which is the timer initial value.2, multithreading (
Everyone said that the timer is not very good, often encounter: if a task in front of the slow, beyond the period, then the next time the timer poll will not be delayed.Colleagues say Scheduleexecutorservice can avoid the problem, I write an example test under:Package Com.dx.testparallel;import Java.util.concurrent.executors;import Java.util.concurrent.scheduledexecutorservice;import Java.util.concurrent.TimeUnit; Public classTesttimer { Public Static voidMain (string[] args) {
maximum number of threads parameter controls the number of concurrent threads in the system.JAVA5 thread PoolJava5 built-in thread pool, the Executors factory class was added to generate the thread pool, which contains several static factory methods to create the threading pools.Executorservice Newcachedthreadpool () creates a buffer-capable thread poolExecutorservice Newfixedthreadpool (int n) creates a reusable thread pool with a fixed number of threadsExecutorservice Newsinglethreadexecutor
()-start)); } }; Timer timeR = new Timer (); Start = System.currenttimemillis (); Timer.schedule (Task1, 1000); Timer.schedule (TASK2, 3000); } }Execution Result:Task1 invoked! 1000Task2 invoked! 4000Newscheduledthreadpool:1. Multiple threads can perform different tasks at the same time.2, because it is a number of threads all, the task throws an exception, does not affect the execution of other tasks.
After scheduleatfixedrate:0s, s
Thinking logic of computer programs (80) and thinking 80
This section describes scheduled tasks. There are many application scenarios for scheduled tasks, such:
An alarm program or task reminder. You can call a bed at a specified time or return a credit card on a specified date.
The monitoring system collects system data at intervals to trigger alarms for abnormal events.
Statistical System, which usually collects various data indicators of yesterday at a certain time in the early morning.
;ExecutorService threadPoolExecutor = new ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueueSecond, ScheduledthreadpoolexecutorScheduledthreadpoolexecutor is another implementation class of Executorservice, from the above Java thread pool Executorservice inheritance tree, as can be seen in the picture, Scheduledthreadpoolexecutor directly inherit from
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.